const db = wx.cloud.database()
const _ = db.command //获取数据库操作的一些指令对象
Page({
    data:{
        detail:{},//存储菜谱详情
        id:'ac5f38825f461f4e005f5f880d9b3204',//菜谱详情的id
        isFllow:false,//默认没有关注
    },
    onShareAppMessage(){//当button的open-type为share,会触发次生命周期
        return{
            title:this.data.detail.recipeName + '的做法'
        }
    },
    onLoad(option){
        let title = option.title || '红烧肉'
        this.data.id = option.id || "ac5f38825f461f4e005f5f880d9b3204"
        this._getReipceDetail()
        this._getReipceView()
        this._userIsFllowRecipe()
        wx.setNavigationBarTitle({
          title: title + '的做法'
        })
    },
    async _setRecipeFllow(){
        // console.log(this.data.id)
        let {_openid} = wx.getStorageSync('userInfo')
        // console.log(_openid)
        if( this.data.isFllow ){
            console.log('去关闭')
            db.collection('re-fllows').where({
                _openid,recipeId:this.data.id
            }).remove()
            this.setData({
                isFllow:false
            })
        }else{
            console.log('要关注')
            db.collection('re-fllows').add({
                data:{
                    recipeId:this.data.id
                }
            })
            this.setData({
                isFllow:true
            })
        }
    },
    // 打开页面，判断登录用户是否关注了次菜谱
    async _userIsFllowRecipe(){
        let { _openid } = wx.getStorageSync('userInfo')
        let fllowsResult = await db.collection('re-fllows').where({
            _openid,
            recipeId:this.data.id
        }).get()
        if( fllowsResult.data.length > 0 ){
            this.setData({
                isFllow:true
            })
        }else{
            this.setData({
                isFllow:false
            })
        }
    },

    // 根据id更新浏览次数
    async _getReipceView(){
        let id = this.data.id
        db.collection('re-recipes').doc(id).update({
            data:{
                views:_.inc(1)
            }
        })
    },
    // 根据id更新收藏次数

    async _getReipceDetail(){//查询当前id的菜谱想起
        let id = this.data.id
        let recipeResult = await db.collection('re-recipes').doc(id).get()
        // console.log(recipeResult)
        this.setData({
            detail:recipeResult.data
        })
    }
})